package secure;

/**
 * Created with IntelliJ IDEA.
 * ClassName: WindowTest
 * Package: secure
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-08-13
 * Time: 13:01
 */

//测试线程不安全 问题
public class WindowTest {
    //三个窗口买1000张火车票
    public static void main(String[] args) {
        Window window = new Window();
        Thread t1 = new Thread(window);
        Thread t2 = new Thread(window);
        Thread t3 = new Thread(window);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class Window implements Runnable {
    //100张票
    private int vote = 100;

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                //循环的买票
                if (vote > 0) {
                    System.out.println(Thread.currentThread().getName() + "售票,票号为: " + vote);
                    //买一张 少一张
                    vote--;
                } else {
                    break;
                }
            }
        }
    }
}

//出现的问题是 买了重复的票